import { AppConfig } from '../react-providers';
import { IApplicationService } from './application';
import { Deferred, OperatingSystem, OS, uuid } from '../utils';

export class ApplicationService implements IApplicationService {
  private readonly appConfig: AppConfig;
  private _backendOS: OperatingSystem;
  private _initialized = new Deferred<void>();

  private wsChannelId: string = uuid();

  constructor(appConfig: AppConfig) {
    this.appConfig = appConfig;
  }

  get frontendOS() {
    return OS.type();
  }

  get backendOS() {
    if (this._backendOS) {
      return this._backendOS;
    }
    // electron 作为 backend，可直接使用 frontend 的 os
    if (this.appConfig.isElectronRenderer) {
      return this.frontendOS;
    }
    throw new Error(
      "Can't get backend os type before initialize, if you want wait to get backend os, please use async method: getBackendOS"
    );
  }

  async getBackendOS() {
    await this._initialized.promise;
    return this.backendOS;
  }

  get clientId(): string {
    return this.wsChannelId;
  }

  get windowId(): string | number {
    if (this.appConfig.isElectronRenderer) {
      const windowId = Math.floor(Math.random() * 100);
      // return electronEnv.currentWindowId;
      return windowId;
    } else {
      // web 场景先用 clientId
      // const channelHandler = this.injector.get(WSChannelHandler);
      // return channelHandler.clientId;
      return '';
    }
  }
}
